package com.taoyibao.hongcanting.dialog;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.RadioGroup;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.DateUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.LunarDateUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.widget.WheelView;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * @author TangAnna
 * @description: 选择日期 可选择阴历可选择阳历阴历阳历切换（两者不关联）
 * @date :${DATA} 15:46
 */
public class DialogChooseDate extends BaseFragmentDialog implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    private RadioGroup mRadioGroup;
    private WheelView mWheelViewYear;
    private WheelView mWheelViewMouth;
    private WheelView mWheelViewDay;
    private DialogChooseDateFace mChooseDateFace;
    private static final String YEAR = "年";
    private static final String MONTH = "月";
    private static final String DAY = "日";
    private int mCurrentYear; //当前年份
    private int mCurrentMonth;//当前月份
    private int mCurrentDay;//当前日期
    private int mDefaultYearIndex;//年份的默认选项是当前年份的下标
    private int mDefaultMonthIndex;
    private int mDefaultDayIndex;

    private LunarDateUtils mLunarDateUtils;//阴历数据源工具类
    private DateUtils mDateUtils;
    private String mLunarDay;//当前的阴历日
    private String mLunarYear;//当前的阴历年份
    private String mLunarMonth;//当前的阴历月份
    private ArrayList<String> mYinLiYearData;
    private ArrayList<String> mYinLiMonthData;
    private ArrayList<String> mYinLiDayData;
    private int mLunarIntDay;//当前阴历int日
    private int mLunarIntMonth;//当前阴历int月
    private int mLunarIntYear;//当前阴历int年

    @Override
    protected int bindView() {
        return R.layout.dialog_choose_date;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mRadioGroup = view.findViewById(R.id.rg_dialogChooseDate_group);
        mWheelViewYear = view.findViewById(R.id.wv_dialogChooseDate_year);
        mWheelViewMouth = view.findViewById(R.id.wv_dialogChooseDate_mouth);
        mWheelViewDay = view.findViewById(R.id.wv_dialogChooseDate_day);
    }

    @Override
    protected void initData() {
        super.initData();
        //获取当前年月日
        Calendar c = Calendar.getInstance();
        mCurrentYear = c.get(Calendar.YEAR);
        //Calendar获取到的月份从0开始计算  实际值要加一
        mCurrentMonth = c.get(Calendar.MONTH) + 1;
        mCurrentDay = c.get(Calendar.DATE);
        mLunarDateUtils = new LunarDateUtils();
        mDateUtils = new DateUtils();
        //获取当前时间的阴历时间
        mLunarDay = mDateUtils.getLunarDate(mCurrentYear, mCurrentMonth, mCurrentDay, true);
        mLunarYear = mDateUtils.getYear() + YEAR;
        mLunarMonth = mDateUtils.getLunarMonth();
        //获取当前时间的阴历时间int类型的
        mLunarIntDay = mDateUtils.getIntDay();
        mLunarIntMonth = mDateUtils.getIntMonth();
        mLunarIntYear = mDateUtils.getYear();
        LogUtils.dNormal("当前阴历日期", mLunarYear + mLunarMonth + mLunarDay);
        LogUtils.dNormal("当前阴历日期", mLunarYear + mDateUtils.getIntMonth() + mDateUtils.getIntDay());
    }

    @Override
    protected void setData() {
        super.setData();
        mWheelViewYear.setData(getYearData());
        mWheelViewYear.setDefault(mDefaultYearIndex);

        mWheelViewMouth.setData(getMonthData());
        mWheelViewMouth.setDefault(mDefaultMonthIndex);

        mWheelViewDay.setData(getDayData(mCurrentYear, mCurrentMonth));
        mWheelViewDay.setDefault(mDefaultDayIndex);
    }

    @Override
    protected void setListener(View view) {
        super.setListener(view);
        mRadioGroup.setOnCheckedChangeListener(this);
        view.findViewById(R.id.tv_dialogChooseDate_cancel).setOnClickListener(this);
        view.findViewById(R.id.tv_dialogChooseDate_confirm).setOnClickListener(this);
        //年份变化
        mWheelViewYear.setOnSelectListener(new WheelView.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                endSelectYear(id, text);
            }

            @Override
            public void selecting(int id, String text) {

            }
        });
        //月份变化
        mWheelViewMouth.setOnSelectListener(new WheelView.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                endSelectMonth();
            }

            @Override
            public void selecting(int id, String text) {

            }
        });
    }

    @Override
    protected int setGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int setAnimation() {
        return 0;
    }

    /**
     * 阴阳历切换
     *
     * @param group
     * @param checkedId
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_dialogChooseDate_yinLi) {
            initYinLi();
        } else if (checkedId == R.id.rb_dialogChooseDate_yangLi) {
            initYangLi();
        }
    }

    /**
     * 切换阳历数据
     */
    public void initYangLi() {

        mWheelViewYear.refreshData(getYearData());
        mWheelViewYear.setDefault(mDefaultYearIndex);

        mWheelViewMouth.refreshData(getMonthData());
        mWheelViewMouth.setDefault(mDefaultMonthIndex);

        mWheelViewDay.refreshData(getDayData(mCurrentYear, mCurrentMonth));
        if (mDefaultDayIndex <= getDayData(mCurrentYear, mCurrentMonth).size()) {
            mWheelViewDay.setDefault(mDefaultDayIndex);
        }
    }

    /**
     * 切换阴历数据
     */
    public void initYinLi() {
        //设置年份数据
        mYinLiYearData = mLunarDateUtils.getYearData(mLunarIntYear);
        mWheelViewYear.refreshData(mYinLiYearData);
        int defauitYearIndex = mDefaultYearIndex;
        for (int i = 0; i < mYinLiYearData.size(); i++) {
            if (TextUtils.equals(mYinLiYearData.get(i), mLunarYear)) {
                defauitYearIndex = i;
                break;
            }
        }
        mWheelViewYear.setDefault(defauitYearIndex);

        //设置月份数据
        mYinLiMonthData = mLunarDateUtils.getMonthData(mLunarIntYear);
        mWheelViewMouth.refreshData(mYinLiMonthData);
        int defauitMonthIndex = mDefaultMonthIndex;
        for (int i = 0; i < mYinLiMonthData.size(); i++) {
            if (TextUtils.equals(mYinLiMonthData.get(i), mLunarMonth)) {
                defauitMonthIndex = i;
                break;
            }
        }
        mWheelViewMouth.setDefault(defauitMonthIndex);

        //设置日数据

        mYinLiDayData = mLunarDateUtils.getDayData(mLunarIntYear, mLunarIntMonth);
        mWheelViewDay.refreshData(mYinLiDayData);
        int defauitDayIndex = mDefaultDayIndex;
        for (int i = 0; i < mYinLiDayData.size(); i++) {
            if (TextUtils.equals(mYinLiDayData.get(i), mLunarDay)) {
                defauitDayIndex = i;
                break;
            }
        }
        if (defauitDayIndex <= mLunarDateUtils.getDayData(mCurrentYear, mCurrentMonth).size()) {
            mWheelViewDay.setDefault(defauitDayIndex);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_dialogChooseDate_cancel://取消
                dismiss();
                break;
            case R.id.tv_dialogChooseDate_confirm://确认
                if (!TextUtils.isEmpty(getDateResult())) {
                    if (mChooseDateFace != null) {
                        mChooseDateFace.onConfirm(getCalenderType(), getDateResult());
                    }
                    dismiss();
                }
                break;
        }
    }

    /**
     * 获取日期类型
     *
     * @return
     */
    public int getCalenderType() {
        if (mRadioGroup.getCheckedRadioButtonId() == R.id.rb_dialogChooseDate_yinLi) {//阴历
            return CodeConstant.DATE_TYPE_YINLI;
        } else if (mRadioGroup.getCheckedRadioButtonId() == R.id.rb_dialogChooseDate_yangLi) {//阳历
            return CodeConstant.DATE_TYPE_YANGLI;
        }
        return -1;
    }

    /**
     * 获取选择的日期的结果
     *
     * @return
     */
    public String getDateResult() {
        String year = mWheelViewYear.getSelectedText();
        String month = mWheelViewMouth.getSelectedText();
        String day = mWheelViewDay.getSelectedText();
        long currentTime = System.currentTimeMillis() / 1000;
        if (getCalenderType() == CodeConstant.DATE_TYPE_YINLI) {
            //当前阴历的yyyy年MM月dd日
            long longYinCurrent = CodeUtils.formatDate(mLunarYear
                    + mDateUtils.getIntMonth() + "月"
                    + mDateUtils.getIntDay() + "日");
            //选中的阴历的yyyy年MM月dd日
            long longYinChoose = CodeUtils.formatDate(mWheelViewYear.getSelectedText()
                    + (mWheelViewMouth.getSelected() + 1) + "月"
                    + (mWheelViewDay.getSelected() + 1) + "日");

            if (longYinCurrent < longYinChoose) {
                ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintChooseDate));
                return "";
            }
            return year + month + day;
        } else if (getCalenderType() == CodeConstant.DATE_TYPE_YANGLI) {
            //转换成long型
            long longTime = CodeUtils.formatDate(year + month + day);
            if (currentTime < longTime) {
                ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintChooseDate));
                return "";
            }
            return CodeUtils.formatDateString2String(year + month + day);
        }
        return "";
    }

    /**
     * 初始化年份数据
     *
     * @return
     */
    private ArrayList<String> getYearData() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = mCurrentYear; i > 1800; i--) {
            list.add(String.valueOf(i) + YEAR);
        }
        mDefaultYearIndex = list.indexOf(mCurrentYear + YEAR);
        return list;
    }

    /**
     * 初始化月份数据
     *
     * @return
     */
    private ArrayList<String> getMonthData() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            list.add(String.valueOf(i) + MONTH);
        }
        mDefaultMonthIndex = list.indexOf(mCurrentMonth + MONTH);
        return list;
    }

    /**
     * 初始化日期数据
     *
     * @param year
     * @param month
     * @return
     */
    private ArrayList<String> getDayData(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0); //输入类型为int类型
        int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);

        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i < dayOfMonth + 1; i++) {
            list.add(String.valueOf(i) + DAY);
        }
        mDefaultDayIndex = list.indexOf(mCurrentDay + DAY);
        return list;
    }


    public interface DialogChooseDateFace {
        void onConfirm(int calenderType, String date);
    }

    /**
     * 确认的回调
     *
     * @param chooseDateFace
     */
    public void setChooseDateFace(DialogChooseDateFace chooseDateFace) {
        mChooseDateFace = chooseDateFace;
    }

    /**
     * 年份变化时回调
     */
    public void endSelectYear(int id, String text) {
        LogUtils.dNormal("年份变化", "id==" + id + "  text== " + text);
        final String year = mWheelViewYear.getSelectedText().replace(YEAR, "");//当前选中的年份
        final String month = mWheelViewMouth.getSelectedText().replace(MONTH, "");
        final int monthIndex = mWheelViewMouth.getSelected();//选中的月份的下标
        if (getCalenderType() == CodeConstant.DATE_TYPE_YINLI) {//阴历
            //年变化时阴历的月份也要变化  日也就要变化
            mWheelViewMouth.post(new Runnable() {
                @Override
                public void run() {
                    mWheelViewMouth.refreshData(mLunarDateUtils.getMonthData(Integer.parseInt(year)));
                    mWheelViewMouth.setDefault(0);
                }
            });

            mWheelViewDay.post(new Runnable() {
                @Override
                public void run() {
                    mWheelViewDay.refreshData(mLunarDateUtils.getDayData(Integer.parseInt(year), 1));
                    mWheelViewDay.setDefault(0);
                }
            });

        } else if (getCalenderType() == CodeConstant.DATE_TYPE_YANGLI) {//阳历
            mWheelViewDay.post(new Runnable() {
                @Override
                public void run() {
                    mWheelViewDay.refreshData(getDayData(Integer.parseInt(year), Integer.parseInt(month)));
                    mWheelViewDay.setDefault(0);
                }
            });
        }
    }

    /**
     * 月份变化时的回调
     */
    public void endSelectMonth() {
        final String year = mWheelViewYear.getSelectedText().replace(YEAR, "");//当前选中的年份
        final int monthIndex = mWheelViewMouth.getSelected();//选中的月份的下标
        final String month = mWheelViewMouth.getSelectedText().replace(MONTH, "");
        if (getCalenderType() == CodeConstant.DATE_TYPE_YINLI) {//阴历
            mWheelViewDay.post(new Runnable() {
                @Override
                public void run() {
                    mWheelViewDay.refreshData(mLunarDateUtils.getDayData(Integer.parseInt(year), monthIndex + 1));
                    mWheelViewDay.setDefault(0);
                }
            });

        } else if (getCalenderType() == CodeConstant.DATE_TYPE_YANGLI) {//阳历
            mWheelViewDay.post(new Runnable() {
                @Override
                public void run() {
                    mWheelViewDay.refreshData(getDayData(Integer.parseInt(year), Integer.parseInt(month)));
                    mWheelViewDay.setDefault(0);
                }
            });
        }
    }
}
